<template>
  <div>
    <TreeSelect
      v-model:value="selectData"
      style="width: 100%"
      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
      :placeholder="placeholder"
      allow-clear
      show-search
      tree-default-expand-all
      :tree-data="treeData"
      :field-names="{ children: 'children', label: 'title', value: 'id' }"
      tree-node-filter-prop="title"
      @select="handleSelect"
      :key="key"
    >
      <template #title="{ systemName, parentId, title }">
        {{ title }}&nbsp;&nbsp;<b v-if="!(parentId > 0)">[{{ systemName }}]</b>
      </template>
    </TreeSelect>
  </div>
</template>
<script lang="ts" setup>
  import { TreeSelect } from 'ant-design-vue';
  import { onMounted, ref, watch } from 'vue';
  import { getMenuTree } from '/@/api/system/menu';
  const treeData = ref<Recordable[]>([]);
  const selectData = ref<string | undefined>('');

  // const value = ref<string>();

  const props = defineProps({
    value: String,
    placeholder: String,
  });

  const emit = defineEmits(['options-change', 'change', 'update:value']);
  const key = ref(0);
  onMounted(() => {
    fetch();
  });

  watch(
    () => props.value,
    () => {
      fetch();
    },
  );

  async function fetch() {
    treeData.value = ((await getMenuTree()) as unknown as Recordable[]) || [];
    selectData.value = props.value;
    emit('options-change', treeData.value);
  }

  //多选
  // function handleChange(...args) {
  //   emit('change', ...args);
  // }

  //单选
  function handleSelect(val, node) {
    selectData.value = val;
    emit('change', val, node);
    key.value++;
  }
</script>
